function a(ele){return document.querySelector(ele)}
function c(ele){return document.createElement(ele)}

//ajax_get
function ajax_get(url){
    return new Promise((resolve,reject)=>{
        let xhr=new XMLHttpRequest()
        xhr.open("get",url,true)
        xhr.send()
        xhr.onreadystatechange=()=>{
            if(xhr.readyState === 4 && xhr.status === 200){
                resolve(xhr.responseText)
            }
        }
    })
}
//ajax_post
function ajax_post(url,str){
    return new Promise((resolve,reject)=>{
        let xhr=new XMLHttpRequest()
        xhr.open("post",url,true)
        xhr.setRequestHeader('content-type','application/x-www-form-urlencoded')
        xhr.send(str)
        xhr.onreadystatechange=()=>{
            if(xhr.readyState === 4 && xhr.status === 200){
                resolve(xhr.responseText)
            }
        }
    })
}

// $(document).ready(function () {
//     $("#search-form-input").keydown(function (e) {
//         var $s = $("#search-form-input").val()
//         if (e.keyCode == 13)
//             console.log("你搜的内容："+$s)
//     })
// })
if(!localStorage.getItem("search")){
    localStorage.setItem("search","[]")
}
a("#search-form-input").onkeypress=function(e){
    if(e.keycode == 13){
        search()
    }
}

function search(){
    let obj={
        product_name:a("#search-form-input").value
    }
    let arr=JSON.parse(localStorage.getItem("local_content"))
    let newArr=[]
    for(let i of arr){
        if(i.product_name == obj.product_name){
            newArr.push(i)
        }
    }
    console.log(newArr)
    if(newArr.length<=0){
        a("section").innerHTML=""
        $("section").text("无搜索结果").addClass("none")
    }else{
        for(let j of newArr){
            a("section").innerHTML=""
            let content=$("<div></div>")
            content.addClass("content").attr("tag",j.id)
            let img=$("<img>")
            img.addClass("img").attr("src","./img/"+j.id+".jpg")
            let product_name=$("<div></div>")
            product_name.addClass("product_name").text(j.product_name)
            let box=$("<div></div>")
            box.addClass("box")
            let product_price=$("<div></div>")
            product_price.addClass("product_price").text("￥"+j.product_price)
            let star=$("<div></div>")
            star.addClass("star").text(Math.ceil(Math.random()*1500))
            box.append($(product_price)).append($(star))
            content.append($(img)).append($(product_name)).append($(box))
            $("section").append($(content))

            //点击content跳转到对应的详细页面
            content.on("click",function(){
                let a=$(this).attr("tag")
                window.location.href="http://localhost/mogujie/detail.html"+"?id="+a
            })
        }
    }
}